from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from day5modelup.settings import BASE_DIR
from two.models import UserModel
from django.core.files.uploadedfile import InMemoryUploadedFile

def index(request):
    return render(request, 'index.html')


def upload_file(request):
    if request.method == "GET":
        return render(request, 'upload.html')
    elif request.method == "POST":
        icon = request.FILES.get("icon")

        print(type(icon))
        print(icon.name)
        print(icon.file)
        print(icon.field_name)
        print(icon.content_type)

        with open(f"{BASE_DIR}/static/files/{icon.name}", 'wb') as save_file:
            for part in icon.chunks():
                save_file.write(part)
                save_file.flush()

        return redirect(reverse('two:upload_file'))


def image_field(request):
    if request.method == "GET":
        return render(request, 'image_field.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        icon = request.FILES.get("icon")
        user = UserModel()
        user.name = username
        user.icon = icon
        print(type(icon))
        print(icon)
        user.save()
        return HttpResponse("上传成功%d" % user.id)


def mine(request):
    username = request.GET.get("username")
    user = UserModel.objects.get(name=username)
    print("/static/upload/"+user.icon.url)
    data = {
        "username": username,
        "icon_url": "/static/upload/"+user.icon.url
    }
    return render(request, 'mine.html', context=data)